<!-- V-webapp/src/views/ActivitiesView.vue -->
<template>
  <div class="activities-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">精彩活动</h1>
      </div>
      <div class="header-actions">
        <el-button type="primary" :icon="Refresh" @click="loadActivities" :loading="loading">
          刷新
        </el-button>
      </div>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section">
      <el-card class="filter-card">
        <div class="filter-content">
          <div class="filter-left">
            <span class="filter-label">活动状态：</span>
            <el-select 
              v-model="filterForm.status" 
              placeholder="全部状态" 
              clearable
              class="status-select"
            >
              <el-option label="全部状态" value=""></el-option>
              <el-option label="待发布" value="pending"></el-option>
              <el-option label="预约中" value="published"></el-option>
              <el-option label="进行中" value="ongoing"></el-option>
              <el-option label="已结束" value="completed"></el-option>
              <el-option label="已取消" value="cancelled"></el-option>
            </el-select>
          </div>
          <div class="filter-right">
            <el-button type="primary" @click="handleSearch" :loading="loading">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="resetFilter">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 错误提示 -->
    <div v-if="error" class="error-tip">
      <el-alert
        :title="error"
        type="error"
        show-icon
        :closable="false"
      />
    </div>

    <!-- 活动列表 -->
    <div class="activities-container">
      <div v-loading="loading" class="activities-grid">
        <!-- 活动卡片 -->
        <div 
          v-for="activity in activities" 
          :key="activity.activity_id"
          class="activity-card"
          @click="$router.push(`/activity/${activity.activity_id}`)"
        >
          <div class="card-cover">
            <img 
              :src="getActivityImage(activity.cover_image)" 
              :alt="activity.title"
              class="cover-image"
            />
            <div class="cover-overlay">
              <el-tag :type="getStatusType(activity.status)" class="status-badge">
                {{ getStatusText(activity.status) }}
              </el-tag>
            </div>
            <div class="participants-count">
              <el-icon><User /></el-icon>
              {{ activity.current_participants || 0 }}
            </div>
          </div>
          
          <div class="card-content">
            <h3 class="activity-title">{{ activity.title }}</h3>
            
            <div class="activity-meta">
              <div class="meta-item">
                <el-avatar 
                  :size="24" 
                  :src="activity.anchor?.avatar || '/default-avatar.jpg'"
                  class="anchor-avatar"
                />
                <span class="anchor-name">{{ activity.anchor?.anchor_name || '未知主播' }}</span>
              </div>
              
              <div class="meta-item">
                <el-icon><Clock /></el-icon>
                <span class="time-text">{{ formatTime(activity.start_time) }}</span>
              </div>
              
              <div class="meta-item">
                <el-icon><Location /></el-icon>
                <span class="location-text">{{ activity.location || '线上活动' }}</span>
              </div>
            </div>
            
            <div class="activity-footer">
              <div class="tags">
                <el-tag v-if="activity.tags" size="small" type="info">
                  {{ activity.tags }}
                </el-tag>
              </div>
              <div class="action-button">
                <el-button type="primary" size="small" text>
                  查看详情
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="activities.length === 0 && !loading" class="empty-state">
          <div class="empty-content">
            <el-icon class="empty-icon"><Calendar /></el-icon>
            <h3>暂无活动</h3>
            <p>暂时没有找到相关活动，去看看其他内容吧</p>
            <el-button type="primary" @click="resetFilter">
              查看全部活动
            </el-button>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-section" v-if="activities.length > 0 && pagination.total > pagination.size">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[12, 24, 36, 48]"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  User, Clock, Location, Search, 
  Refresh, Calendar 
} from '@element-plus/icons-vue'
import { getActivities } from '@/api/activities'

// 导入本地活动图片
import liangzhounian from '@/assets/images/liangzhounian.png'
import activity150W from '@/assets/images/150W.jpg'
import defaultActivityImg from '@/assets/images/S1.jpg'

const activities = ref<any[]>([])
const loading = ref(false)
const error = ref('')

const filterForm = reactive({
  status: ''
})

const pagination = reactive({
  current: 1,
  size: 12,
  total: 0
})

// 图片映射表
const imageMap = {
  'liangzhounian.png': liangzhounian,
  '150W.jpg': activity150W,
  'S1.jpg': defaultActivityImg
}

// 获取活动图片
const getActivityImage = (coverImage: string) => {
  if (!coverImage) return defaultActivityImg
  return imageMap[coverImage] || defaultActivityImg
}

// 状态映射函数
const getStatusText = (status: string) => {
  const statusMap: any = {
    'pending': '待发布',
    'published': '预约中', 
    'ongoing': '进行中',
    'completed': '已结束',
    'cancelled': '已取消'
  }
  return statusMap[status] || status
}

const getStatusType = (status: string) => {
  const statusMap: any = {
    'pending': 'info',
    'published': 'warning',
    'ongoing': 'success',
    'completed': 'info',
    'cancelled': 'danger'
  }
  return statusMap[status] || 'info'
}

const loadActivities = async () => {
  loading.value = true
  error.value = ''
  
  try {
    const params = {
      page: pagination.current,
      limit: pagination.size,
      ...filterForm
    }
    
    const result = await getActivities(params)
    console.log('🎯 活动列表响应:', result)
    
    // 适配不同的响应结构
    if (result.success) {
      activities.value = result.data || []
      pagination.total = result.pagination?.total || 0
    } else if (result.code === 200) {
      activities.value = result.data?.list || result.data || []
      pagination.total = result.data?.total || result.pagination?.total || 0
    } else {
      // 如果响应不成功，但data存在，也显示数据
      activities.value = result.data || []
      if (result.message && result.message !== '获取活动列表成功') {
        error.value = result.message
        ElMessage.error(result.message)
      }
    }
    
  } catch (err: any) {
    console.error('加载活动数据错误:', err)
    error.value = err.message || '网络请求失败'
    ElMessage.error('加载活动数据失败')
  } finally {
    loading.value = false
  }
}

const formatTime = (time: string) => {
  if (!time) return '时间待定'
  const date = new Date(time)
  const now = new Date()
  const diff = date.getTime() - now.getTime()
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (days === 0) {
    return '今天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  } else if (days === 1) {
    return '明天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  } else if (days === -1) {
    return '昨天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  } else {
    return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadActivities()
}

const resetFilter = () => {
  filterForm.status = ''
  pagination.current = 1
  loadActivities()
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  loadActivities()
}

const handleCurrentChange = (page: number) => {
  pagination.current = page
  loadActivities()
}

onMounted(() => {
  loadActivities()
})
</script>

<style scoped>
/* 样式保持不变 */
.activities-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
}

.header-content {
  color: white;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 700;
}

.page-subtitle {
  margin: 0;
  opacity: 0.9;
  font-size: 16px;
}

.filter-section {
  margin-bottom: 24px;
}

.filter-card {
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.filter-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.filter-label {
  font-weight: 500;
  color: #606266;
}

.status-select {
  width: 140px;
}

.error-tip {
  margin-bottom: 16px;
}

.activities-container {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.activities-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.activity-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  cursor: pointer;
  border: 1px solid #f0f0f0;
}

.activity-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.card-cover {
  position: relative;
  height: 180px;
  overflow: hidden;
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.activity-card:hover .cover-image {
  transform: scale(1.05);
}

.cover-overlay {
  position: absolute;
  top: 12px;
  left: 12px;
}

.status-badge {
  font-weight: 600;
  border: none;
}

.participants-count {
  position: absolute;
  top: 12px;
  right: 12px;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.card-content {
  padding: 16px;
}

.activity-title {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.activity-meta {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 12px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  color: #606266;
}

.anchor-avatar {
  flex-shrink: 0;
}

.anchor-name {
  font-weight: 500;
}

.time-text, .location-text {
  font-size: 12px;
}

.activity-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 12px;
  border-top: 1px solid #f5f5f5;
}

.tags {
  flex: 1;
}

.action-button :deep(.el-button) {
  padding: 4px 12px;
  font-size: 12px;
}

.empty-state {
  grid-column: 1 / -1;
  text-align: center;
  padding: 60px 20px;
}

.empty-content {
  max-width: 300px;
  margin: 0 auto;
}

.empty-icon {
  font-size: 64px;
  color: #c0c4cc;
  margin-bottom: 16px;
}

.empty-content h3 {
  margin: 0 0 8px 0;
  color: #606266;
  font-size: 18px;
}

.empty-content p {
  margin: 0 0 20px 0;
  color: #909399;
  font-size: 14px;
}

.pagination-section {
  display: flex;
  justify-content: center;
  padding-top: 24px;
  border-top: 1px solid #f0f0f0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .activities-page {
    padding: 12px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .filter-content {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .filter-left {
    justify-content: center;
  }
  
  .filter-right {
    display: flex;
    gap: 8px;
  }
  
  .activities-grid {
    grid-template-columns: 1fr;
  }
}
</style>